<template>
  <div>
    <div class="pageCard">
      <a-form layout="inline" :model="formSearch" style="align-items: center">
        <a-form-item>
          <a-select
            allowClear
            style="width: 200px"
            v-model:value="formSearch.deviceClassifyId"
            placeholder="请选择设备类型"
          >
            <a-select-option
              v-for="item in deviceClassifyList"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-select
            allowClear
            style="width: 200px"
            v-model:value="formSearch.status"
            placeholder="请选择"
          >
            <a-select-option
              v-for="item in statusList"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-tree-select
            allowClear
            v-model:value="formSearch.hospitalDepartId"
            style="width: 200px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="departmentList"
            placeholder="请选择科室"
            tree-default-expand-all
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item>
          <a-input
            allowClear
            v-model:value="formSearch.keyWord"
            placeholder="请输入设备名称/设备编号/责任人"
          >
          </a-input>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="getSearch">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="toresetFields">重置</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div style="background: #fff">
      <a-table
        style="padding: 0 20px"
        :pagination="pagination"
        :columns="columns"
        :rowKey="(record) => record.id"
        :data-source="list"
        :row-selection="rowSelection"
        :scroll="{ x: 1500 }"
      >
        <template #status="{ record }">
          <div>
            {{ record.status == "unused" ? "未使用" : "正常使用" }}
          </div>
        </template>
        <template #operation="{ record }">
          <div style="display: flex; align-items: center">
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_blue"
              @click="lookHandle(record)"
            >
              查看
            </div>
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_blue"
              @click="editHandle(record)"
            >
              编辑
            </div>
           
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_red"
              @click="delHandle(record)"
            >
              删除
            </div>
          </div>
        </template>
        <template #title>
          <div class="ANTTable_header">
            <div style="font-weight: bold">设备信息维护</div>
            <div>
              <a-button @click="handleImport" style="margin: 0 10px"
                >导入设备</a-button
              >

              <a-button type="primary" @click="addHandle()"
                >添加设备</a-button
              >
            </div>
          </div>
        </template>
      </a-table>
    </div>

    <a-modal
      width="40%"
      v-model:visible="visible"
      :title="handleTitle"
      @ok="handleOk"
      @cancel="handleCancle"
      ok-text="确认"
      cancel-text="取消"
    >
      <child
        v-if="visible"
        :handleType="handleType"
        :handleRow="handleRow.data"
        ref="child"
        @finish="finishHandle"
      ></child>
    </a-modal>

    <a-modal
      width="40%"
      v-model:visible="ImportFilevisible"
      title="导入设备"
      @ok="ImporthandleOk"
      ok-text="确认上传"
      cancel-text="取消"
    >
      <a-upload-dragger v-model:fileList="fileList" name="file"  accept="application/vnd.ms-excel" :before-upload="beforeUpload" >
        <p class="ant-upload-drag-icon">
          <inbox-outlined></inbox-outlined>
        </p>
        <a-button @click.stop="ImporthandleCancle()">下载模板</a-button>
        <p class="ant-upload-text">第一步:下载Excel设备模板;</p>
        <p class="ant-upload-text">
          第二步:使用模板编辑设备,点击"选择文件"选择您编辑好的Excel文档;
        </p>
        <p class="ant-upload-text">第三步:点击"确认上传"完成设备导入;</p>
      </a-upload-dragger>
    </a-modal>
  </div>
</template>
<script>
import child from "./components/child.vue";
import { createVNode, onMounted, reactive, ref, toRefs, watch } from "vue";
import * as utils from "@/utils/index.js";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { Form } from "ant-design-vue";
import { Modal, message } from "ant-design-vue";
import { getUserInfo } from "@/utils/auth";
import * as deviceBaseApi from "@/api/deviceBase.js";
import * as deviceClassifyApi from "@/api/deviceClassify.js";
import { hospitalDepartList } from "@/api/hospitalDepart.js";
const statusList = [
  // normal：正常使用 unused 未使用
  {
    label: "全部",
    value: "",
  },
  {
    label: "正常使用",
    value: "normal",
  },
  {
    label: "未使用",
    value: "unused",
  },
];
// 表格Column
const columns = [
  {
    title: "设备编号",
    dataIndex: "code",
      width: 180,
  },
  {
    title: "设备名称",
    dataIndex: "name",
     width: 120,
  },
  {
    title: "设备类型",
    dataIndex: "deviceClassifyName",
     width: 120,
  },
  {
    title: "型号",
    dataIndex: "model",
     width: 120,
  },
  {
    title: "启用日期",
    dataIndex: "useDate",
      width: 180,
  },
  {
    title: "使用科室",
    dataIndex: "hospitalDepartName",
     width: 120,
  },
  {
    title: "责任人",
    dataIndex: "userStaffName",
     width: 120,
  },
  {
    title: "状态",
    dataIndex: "status",
    slots: { customRender: "status" },
     width: 100,
  },
  {
    title: "备注",
    dataIndex: "remark",
     width: 160,
  },

  {
    title: "操作",
    dataIndex: "operation",
    width: 250,
    slots: { customRender: "operation" },
  },
];
const useForm = Form.useForm;
export default {
  components: {
    child,
    ExclamationCircleOutlined,
  },
  setup(props, { emit }) {
    const formSearch = reactive({
      // 关键字
      keyWord: "",
      // 所属部门
      hospitalDepartId: null,
      // 设备id
      deviceClassifyId: null,
      // 状态
      status: null,
    });
    const userInfo = ref(getUserInfo() ? JSON.parse(getUserInfo()) : {});
    const tableData = reactive({ list: [], total: 0 });
    const { resetFields } = useForm(formSearch);
    const pageSize = ref(10);
    const pageIndex = ref(1);
    // 查询
    const getSearch = () => {
      console.log(333);
      pageIndex.value = 1;
      pagination.current = 1;
      handleGetDataList();
    };
       const beforeUpload = ()=>{
      return false
    }
    const deviceClassifyList = ref([]);
    //获取设备列表
    const handleGetDeviceList = () => {
      deviceClassifyApi.deviceClassifyList({ isPage: false }).then((res) => {
        if (res && res.success) {
          deviceClassifyList.value = res.data;
        }
      });
    };

    const pagination = reactive({
      total: 0,
      current: pageIndex.value,
      pageSize: pageSize.value, // 默认每页显示数量
      showSizeChanger: true, // 显示可改变每页数量
      pageSizeOptions: [ "10", "20", "30", "40"], // 每页数量选项
      showTotal: (total) => `总数 ${total}条数据`, // 显示总数
      onChange: (page, size) => {
        onPageChange(page, size);
      }, // 改变每页数量时更新显示
      onShowSizeChange: (current, size) => {
        onSizeChange(current, size);
      },
    });
    // 分页
    const onSizeChange = (current, size) => {
      pageIndex.value = 1;
      pagination.current = 1;
      pageSize.value = size;
      handleGetDataList();
    };
    const onPageChange = (current, size) => {
      pageIndex.value = current;
      pagination.current = current;
      handleGetDataList();
    };
    // 获取表格
    const handleGetDataList = async () => {
      tableData.list = [];
      let params = {
        ...formSearch,
        pageIndex: pageIndex.value,
        pageSize: pageSize.value,
      };
      deviceBaseApi.deviceBaseList(params).then((res) => {
        if (res && res.success) {
          console.log(123);
          console.log(res);
          tableData.list = res.data;
          pagination.total = res.total;
        }
      });
    };
    const tableSelectedRows = ref([]);
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        tableSelectedRows.value = selectedRows;
      },
      onSelect: (record, selected, selectedRows) => {
        console.log(record, selected, selectedRows);
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        console.log(selected, selectedRows, changeRows);
      },
    };

    // 重置表格
    const toresetFields = () => {
      resetFields();
      getSearch();
    };
    // 监听表格
    watch(
      () => formSearch,
      (curAge, preAge) => {
        getSearch();
      },
      { deep: true }
    );
    // 获取科室数据
    const departmentList = ref([]);
    const getKSData = async () => {
      let res = await hospitalDepartList({
        isPage: false,
        name: "",
      });
      if (res && res.success) {
        let departmentListO = res.data.map((item) => {
          item.label = item.name;
          item.value = item.id;
          return item;
        });
        departmentList.value = utils.treeDataTranslate(departmentListO);
        console.log(123444444);
        console.log(departmentList.value);
      }
    };
    //  新增功能
    const visible = ref(false);
    const handleType = ref("add");
    const handleTitle = ref("新增设备");
    const handleRow = reactive({ data: {} });
    const addHandle = () => {
      visible.value = true;
      handleType.value = "add";
      handleTitle.value = "新增设备";
    };
    const lookHandle = (data) => {
      visible.value = true;
      handleType.value = "look";
      handleTitle.value = "查看设备";
      handleRow.data = {
        ...data,
      };
    };
    const editHandle = (data) => {
      visible.value = true;
      handleType.value = "edit";
      handleTitle.value = "编辑设备";
      handleRow.data = {
        ...data,
      };
    };
    // 删除
    const delHandle = (data) => {
      Modal.confirm({
        title: () => "提示",
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () =>
          createVNode("div", { style: "color:red;" }, "确认删除该设备"),
        onOk() {
          deviceBaseApi.deviceBaseRemove(data.id).then((res) => {
            if (res && res.success) {
              message.success("删除成功");
              getSearch();
            }
          });
        },
        onCancel() {
          console.log("Cancel");
        },
        class: "test",
      });
    };
    //导入
    const handleImport = () => {
      ImportFilevisible.value = true;
    };
 
    // 完成操作
    const finishHandle = () => {
      visible.value = false;
      getSearch();
    };

    const child = ref(null);
    const handleOk = () => {
      child.value.handleSave();
    };

    const handleCancle = () => {
      child.value.resetForm();
    };

    // 导入功能
    const ImportFilevisible = ref(false);
    const fileList = ref([]);

    const ImporthandleOk = () => {
      console.log(fileList.value[0].originFileObj);
      let formDate = new FormData();
      formDate.append("file", fileList.value[0].originFileObj);
      deviceBaseApi.importList(formDate).then((res) => {
        if (res && res.success) {
          message.success("导入成功");
          ImportFilevisible.value = false;
          getSearch();
        }
      });
    };

    const ImporthandleCancle = () => {
      deviceBaseApi.downloadTemplate().then((res) => {
        const link = document.createElement("a");
        const blob = new Blob([res], {
          type: "application/vnd.ms-excel", // "application/zip",
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = "设备"; // 下载后文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });

      return false;
    };
    onMounted(() => {
      handleGetDataList();
      handleGetDeviceList();
      getKSData();
    });
    return {
      child, //子组件
      // 设备列表
      deviceClassifyList,
      beforeUpload,
      statusList,
      formSearch,
      toresetFields,
      userInfo,
      columns,
      ...toRefs(tableData),
      handleGetDataList,
      getSearch,

      visible,
      addHandle,
      editHandle,
      lookHandle,
      handleTitle,
      handleRow,
      handleType,
      handleOk,
      handleCancle,
      finishHandle,

      delHandle,
      pagination,

      ImportFilevisible,
      fileList,
      ImporthandleOk,
      ImporthandleCancle,
      handleImport,
      rowSelection,
      tableSelectedRows,

      departmentList,
      getKSData,
    };
  },
};
</script>